//
//  BuyViewController.m
//  MyMovie
//
//  Created by Weiwei on 16/2/24.
//  Copyright © 2016年 bever贝沃汇力 weiwei. All rights reserved.
//

#import "BuyViewController.h"
#import "SegmentView.h"
#import "HotMovieCell.h"
#import "HotMovieModel.h"
#import "WillCollectionViewCell.h"
#import "AttentionModel.h"
#import "ComingTableViewCell.h"
#import "ComingModel.h"
@interface BuyViewController (){
    UITableView* _tableView1;
    UITableView* _tableView2;
    
    NSMutableArray* _dataList;//tableVie1
    NSMutableArray* _dataList2;//tableView2 headerView
    
    NSMutableDictionary* _monthsDic;
    NSArray* _allKeys;//所有的月份
    
}

@end

@implementation BuyViewController


//重写init方法，在viewC被创建的时候就给他的navigationItem和tabBarItem
-(id)init{
    if (self = [super init]) {
        
        
        self.navigationItem.title = @"优惠";
        self.tabBarItem.image = [UIImage imageNamed:@"index_menu_coup"];
        
        
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
#pragma -mark 数据解析
    [self loadData];
    
    
    //在self.view增加一个segment
    [self createSegmentView];
    

    [self createTableViews];
    
    
    
}
-(void)loadData{
    
    
    //1.通过数据解析类获得根数句结构
    NSDictionary* rootDataDic = [DataParser jsonObjectFromFileName:@"buy_now"];
    //2.从根数句结构获得电影数组
    NSArray* array = [rootDataDic objectForKey:@"ms"];
    
    //3.创建一个可变数组用于接受model
    _dataList = [[NSMutableArray alloc]initWithCapacity:1];
    
    for (NSDictionary * dic in array) {
        
        HotMovieModel* model = [[HotMovieModel alloc]initWithDic:dic];
        
        [_dataList addObject:model];
        
    }
    
    //----------tableView2增加数据-----
    
    //头试图的数据
    _dataList2 = [[NSMutableArray alloc]init];
    //1.解析更数据
    NSDictionary* rootDataDic1 = [DataParser jsonObjectFromFileName:@"buy_new"];
    //2.获得数组
    NSArray* attentionArray = [rootDataDic1 objectForKey:@"attention"];
    
    for (NSDictionary* dic in attentionArray) {
        
        AttentionModel* model = [[AttentionModel alloc]initWithDic:dic];
        [_dataList2 addObject:model];
        
    }
    
    //tableView2的数据
    //1.解析数据
    NSDictionary* rootDataDic2 = [DataParser jsonObjectFromFileName:@"buy_new"];
    //2.获得数组
    NSArray* comingArray = [rootDataDic2 objectForKey:@"moviecomings"];
    
    //--------将model分组存放到月份数组，月份数组存到dic----
    
    //创建一个字典存储月份分组
    _monthsDic = [[NSMutableDictionary alloc]initWithCapacity:1];
    //取出一个个model字典
    for (NSDictionary* subDic in comingArray) {
        
        ComingModel* model = [[ComingModel alloc]initWithDic:subDic];
        
        //Model有了要分开存
        //先判断model的月份，看看指点中有没有该月份的分组
        //（1）取出model的月份,(nsnumber可以直接用%@打印拼接)
        NSString* month = [NSString stringWithFormat:@"%@",model.rMonth];
        //（2）查看字典有无此分组
       NSMutableArray* monthArray = [_monthsDic objectForKey:month];
        
        if (monthArray == nil) {
            //不存在此分组
            //(1) 创建一个可变数组
            monthArray = [[NSMutableArray alloc]initWithCapacity:1];
            //(2)将model存进去
            [monthArray addObject:model];
            //(3)将数组存到字典中，key为当前月份
            [_monthsDic setObject:monthArray forKey:month];
            
        }else{
            
            //存入数组，更新字典
            [monthArray addObject:model];
            [_monthsDic setObject:monthArray forKey:month];
            
        }
    }
    
    //获得字典中的所有的月份key
     _allKeys = [_monthsDic allKeys];
     _allKeys = [_allKeys sortedArrayUsingSelector:@selector(compare:)];
    
    
    
}





-(void)createSegmentView{
    
    //1.创建
    SegmentView* _segment = [[SegmentView alloc]initWithFrame:CGRectMake(0, 0, KScreenW, 50) withTitleArray:@[@"正在热映",@"即将上映"]];
    //_segment.backgroundColor = [UIColor greenColor];
    
    [self.view addSubview:_segment];
    
    
#pragma -mark 调用方法
    //首先self必须转换成__weak对象才能解除可能存在的相互持有问题
    __weak BuyViewController* weakSelf = self;
    
    //2.
    [_segment setSegmentBlock:^(NSInteger index) {
      
        //获得weakself转换成strongSelf调用方法
        __strong BuyViewController* strongSelf = weakSelf;
        
        [strongSelf moveTableView:index];
        
        
    }];
    
    
}

#pragma -mark 封装一个页面平移的方法，通过传入的index

-(void)moveTableView:(NSInteger)index{
    
    //如果index == 0 第一个页面的frame.x = 0;
    //index == 1. frame.x = 1* -width
    //index == 2. frame.x = 2* -width
    //frame.x = index * - width
    
    [UIView animateWithDuration:.3 animations:^{
        
        
        _tableView1.frame = CGRectMake(index * -KScreenW, 50, KScreenW, _tableView1.frame.size.height);
        
        _tableView2.frame = CGRectMake(_tableView1.frame.origin.x+ KScreenW, 50, KScreenW, _tableView2.frame.size.height);
        
        
        
    }];
    
    
    

    
    
    
    
}






-(void)createTableViews{
    

    
    
    //设置两个全局的tableView1,tableView2
#pragma -mark tableView1
    //1.初始化tableView1,高减去segment和tabBar
    _tableView1 = [[UITableView alloc]initWithFrame:CGRectMake(0, 50, KScreenW, KScreenH - 64 - 50-49) style:UITableViewStylePlain];
    //2.设置背景颜色为红色
    //    _tableView1.backgroundColor = [UIColor redColor];
    _tableView1.backgroundColor = [UIColor clearColor];
    
    //3.设置代理，先没有数据
    _tableView1.delegate =self;
    _tableView1.dataSource = self;
    //4.加载到self.view 上
    [self.view addSubview:_tableView1];
    
#pragma -mark tableView2
    _tableView2 = [[UITableView alloc]initWithFrame:CGRectMake(KScreenW, 50, KScreenW, KScreenH- 64-50-49) style:UITableViewStylePlain];
   // _tableView2.backgroundColor = [UIColor greenColor];
    _tableView2.backgroundColor = [UIColor clearColor];
    //设置代理
    _tableView2.delegate = self;
    _tableView2.dataSource = self;
    [self.view addSubview:_tableView2];
    
#pragma -mark 步骤一创建一个view作为tableView2的头试图
    //1.创建一个头试图
    UIView* headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _tableView2.frame.size.width, 200)];
    //2.设置一个颜色
   // headerView.backgroundColor = [UIColor redColor];
    
    //3.增加lable
    UILabel* lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, headerView.frame.size.width, 30)];
    lable.textColor = [UIColor whiteColor];
    lable.text = @"最受关注";
    lable.font = [UIFont systemFontOfSize:20];
    [headerView addSubview:lable];
    
    //---collectionView部分----
    //1.创建布局类
    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc]init];
    //2.水平滑动
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    //3.设置item大小
    layout.itemSize = CGSizeMake(KScreenW -10, 150);
    
    UICollectionView* _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 30, KScreenW, 170) collectionViewLayout:layout];
    //4.注册代理
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    
    _collectionView.backgroundColor = [UIColor clearColor];
    
    //5.注册单元格
    [_collectionView registerNib:[UINib nibWithNibName:@"WillCollectionViewCell" bundle:[NSBundle mainBundle]]forCellWithReuseIdentifier:@"will_cell"];
    
    //分页效果
    _collectionView.pagingEnabled = YES;
    

    //6.加到headerView上
    [headerView addSubview:_collectionView];
    _tableView2.tableHeaderView = headerView;
    

    
}
//---------collectionView----------

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
//    return 5;
    return _dataList2.count;
    
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
 
    WillCollectionViewCell* cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"will_cell" forIndexPath:indexPath];
    
    //获得当前的数据
    AttentionModel* model = [_dataList2 objectAtIndex:indexPath.row];
    cell.model = model;
    
    return cell;
    
    
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    return UIEdgeInsetsMake(0, 0, 0, 10);
    
}









//---------tableView----------------
#pragma -mark 步骤二实现代理
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == _tableView1) {
//        return 30;
        
        return _dataList.count;
        
        
    }else{
        
//        return 20;
        
        //确定当前月份数组
       NSArray* array = [_monthsDic objectForKey:_allKeys[section]];
      return array.count;
        
        
    }
    
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (tableView == _tableView1) {
    
        //1.使用复用池查找
        HotMovieCell* cell = [tableView dequeueReusableCellWithIdentifier:@"hot_cell"];
        
        if (cell == nil) {
            
            cell = [[[NSBundle mainBundle]loadNibNamed:@"HotMovieCell" owner:nil options:nil]lastObject];
        }
        
        //1.获得当前cell的model
        HotMovieModel* model = [_dataList objectAtIndex:indexPath.row];
        cell.hotMovieModel = model;
        
        
        
        
        
        return cell;
        
    }else{
        
        //使用tableView2的单元格
        //1.重复泳池中查找提取
      ComingTableViewCell* cell  = [tableView dequeueReusableCellWithIdentifier:@"coming_cell"];
        if (cell == nil) {
            
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ComingTableViewCell" owner:nil options:nil]lastObject];
            
            cell.backgroundColor = [UIColor clearColor];
        
        }
        
        //加载数据，别忘了给cell增加model属性
        //1.获取当前的cell的model的组
        NSArray* array =[_monthsDic objectForKey:_allKeys[indexPath.section]];
        //2.获得model
        ComingModel* model = [array objectAtIndex:indexPath.row];
        
        cell.model = model;
        
        
        
        return cell;
        
        
    }

    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _tableView1) {
        return 120;
    }
    return 120;
    
}

//------------新增代理方法----------
//多少组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (tableView == _tableView2) {
        return _allKeys.count;
    }
    
    return 1;
    
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    //1.创建一个imageView
    UIImageView* imageView = [[UIImageView alloc]initWithFrame:CGRectZero];
    imageView.image = [UIImage imageNamed:@"ico_index_title_1"];
    
    //2.添加lable
    UILabel* lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, KScreenW, 25)];
    [imageView addSubview:lable];
    
    lable.textColor  = [UIColor whiteColor];
    lable.font = [UIFont systemFontOfSize:22];
    
    lable.text = [NSString stringWithFormat:@" %@月",_allKeys[section]];
    
    
    return imageView;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (tableView == _tableView2) {
        return 25;
    }
    
    return 0;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
